package com.master.controller;

import com.master.config.HostHolder;
import com.master.domain.MiaoshaUser;
import com.master.redis.GoodsKey;
import com.master.redis.RedisServer;
import com.master.service.GoodsService;
import com.master.service.MiaoshaUserService;
import com.master.util.Result;
import com.master.vo.GoodsDetailVo;
import com.master.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    private static Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    RedisServer redisServer;

    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    HostHolder hostHolder;


    //跳转到商品列表页
    @RequestMapping(value = "/to_list",produces = "text/html")//produces属性代表指定返回的类型
    @ResponseBody
    public String toList(Model model,HttpServletResponse response,
                         HttpServletRequest request){
        model.addAttribute("user",hostHolder.getUser());
        //商品的页面缓存
        String html = redisServer.get(GoodsKey.getGoodsList,"",String.class);
        if(!StringUtils.isEmpty(html)){
            //不是空,直接返回,否则手动渲染
            return html;
        }

        //从数据库中查询商品信息
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList",goodsList);
        //手动渲染
        SpringWebContext ctx = new SpringWebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap(),applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list",ctx);
        if(!StringUtils.isEmpty(html)) {
            //如果不为空,将页面保存到缓存中
            //这个页面缓存有效期设置为60秒,缓存时间不能过长
            redisServer.set(GoodsKey.getGoodsList, "", html);
        }
        return html;//返回页面
    }

    //商品详情页
    @RequestMapping("/to_detail/{goodsId}")
    public String toDetail(Model model,
                           @PathVariable("goodsId")long goodsId){
        model.addAttribute("user",hostHolder.getUser());
       GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        model.addAttribute("goods",goods);

        long startAt = goods.getStartDate().getTime();//秒杀开始时间
        long endAt = goods.getEndDate().getTime();//秒杀结束时间
        long now = System.currentTimeMillis();//当前时间
        //秒杀的状态
        int miaoshaStatus = 0;
        int remainSeconds = 0;//还剩余的时间
        if(now < startAt){
            //秒杀还未开始
            miaoshaStatus = 0;
            remainSeconds = (int)(startAt - now)/1000;
        }else if (now > endAt){
            //秒杀已结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        }else{
            //秒杀正在进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus",miaoshaStatus);//秒杀的状态
        model.addAttribute("remainSeconds",remainSeconds);//秒杀剩余时间
        return "goods_detail";
    }

    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> detail(Model model,
                                          @PathVariable("goodsId")long goodsId){

        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        long startAt = goods.getStartDate().getTime();//秒杀开始时间
        long endAt = goods.getEndDate().getTime();//秒杀结束时间
        long now = System.currentTimeMillis();//当前时间
        //秒杀的状态
        int miaoshaStatus = 0;
        int remainSeconds = 0;//还剩余的时间
        if(now < startAt){
            //秒杀还未开始
            miaoshaStatus = 0;
            remainSeconds = (int)(startAt - now)/1000;
        }else if (now > endAt){
            //秒杀已结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        }else{
            //秒杀正在进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        GoodsDetailVo vo = new GoodsDetailVo();
        vo.setGoodsVo(goods);
        vo.setMiaoshaUser(hostHolder.getUser());
        vo.setRemainSeconds(remainSeconds);
        vo.setMiaoshaStatus(miaoshaStatus);
        return Result.success(vo);
    }


}
